package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.CartBean;
import com.project.bean.UserBean;
import com.project.mapper.ICartMapper;
import com.project.mapper.IUserMapper;
import com.project.service.ICartService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements ICartService {
    @Autowired
    private ICartMapper cartMapper;

    @Override
    public List<CartBean> findByUserId(Integer userId) {
        return cartMapper.findByUserId(userId);
    }

    @Override
    public void addCart(Integer productId, Integer userId) {
        QueryWrapper<CartBean> qw = new QueryWrapper<>();
        qw.eq("fk_productId", productId);
        qw.eq("fk_userId", userId);
        Long count = cartMapper.selectCount(qw);
        if (count == 0) { //购物车中没有该商品
            CartBean cart = new CartBean(productId, userId, 1);
            cartMapper.insert(cart);
        } else {
            CartBean cart = cartMapper.selectOne(qw);
            cart.setBuyNum(cart.getBuyNum() + 1);
            cartMapper.updateById(cart);
        }
    }

    @Override
    public void del(Integer cartId) {
        cartMapper.deleteById(cartId);
    }

    @Override
    public void updateNum(Integer carId, Integer num) {
       CartBean cart= cartMapper.selectById(carId);
       cart.setBuyNum(num);
       cartMapper.updateById(cart);
    }
}
